{% extends "后台管理/template.html" %}

{% block title %}版本管理{% endblock %}

{% block css %}
<style>
    .version-card {
        transition: all 0.3s ease;
    }
    
    .version-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    /* 更新类型徽章样式 */
    .type-badge-primary { background-color: #71dd37 !important; }  /* 新增 - 绿色 */
    .type-badge-info { background-color: #03c3ec !important; }     /* 优化 - 蓝色 */
    .type-badge-danger { background-color: #ff3e1d !important; }   /* 修复 - 红色 */
    .type-badge-secondary { background-color: #8592a3 !important; }/* 删除 - 灰色 */

    /* Toast 通知样式 */
    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
    }
    
    .toast-notification {
        padding: 12px 24px;
        border-radius: 8px;
        margin-bottom: 10px;
        min-width: 300px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        animation: slideIn 0.3s ease;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    .toast-success {
        background-color: #28a745;
        color: white;
    }
    
    .toast-error {
        background-color: #dc3545;
        color: white;
    }
    
    .toast-warning {
        background-color: #ffc107;
        color: #000;
    }
    
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes fadeOut {
        from {
            opacity: 1;
        }
        to {
            opacity: 0;
        }
    }

    .toast-notification .btn-close {
        padding: 0.5rem;
        margin: -0.5rem -0.5rem -0.5rem 0.5rem;
        width: 1.5em;
        height: 1.5em;
        opacity: 0.8;
        cursor: pointer;
        background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
    }

    .toast-notification .btn-close:hover {
        opacity: 1;
    }

    /* 版本说明列表样式 */
    .version-desc-list {
        max-height: 300px;
        overflow-y: auto;
        scrollbar-width: thin;
    }

    .version-desc-list::-webkit-scrollbar {
        width: 6px;
    }

    .version-desc-list::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    .version-desc-list::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 3px;
    }

    .version-desc-list::-webkit-scrollbar-thumb:hover {
        background: #555;
    }

    /* 版本说明折叠样式 */
    .desc-collapse {
        position: relative;
    }

    .desc-collapse.collapsed {
        max-height: 150px;
        overflow: hidden;
    }

    .desc-collapse.collapsed::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 50px;
        background: linear-gradient(transparent, white);
    }

    .show-more-btn {
        width: 100%;
        text-align: center;
        margin-top: 10px;
        color: #696cff;
        cursor: pointer;
        font-size: 0.875rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold py-3 mb-4">版本管理</h4>
        <div class="d-flex align-items-center">
            <div class="me-3">
                <span class="badge bg-primary fs-6" id="currentVersion">
                    <i class="bx bx-code-alt me-1"></i>
                    当前版本: 加载中...
                </span>
            </div>
            <button class="btn btn-primary" onclick="openCreateVersionModal()">
                <i class="bx bx-plus me-1"></i> 创建新版本
            </button>
        </div>
    </div>

    <!-- 版本列表 -->
    <div class="row g-4" id="versionList">
        <!-- 版本卡片将通过JS动态加载 -->
    </div>

    <!-- 版本说明详情模态框 -->
    <div class="modal fade" id="versionDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">版本详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h4 id="detailVersionNumber">版本 x.x.x</h4>
                            <small class="text-muted" id="detailCreateTime">发布时间: xxxx-xx-xx</small>
                        </div>
                        <div class="mb-3">
                            <strong>下载链接：</strong>
                            <a href="#" id="detailDownloadUrl" target="_blank">点击下载</a>
                        </div>
                    </div>
                    <div class="version-desc-list">
                        <h5 class="mb-3">更新说明</h5>
                        <div id="detailDescList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 创建版本模态框 -->
    <div class="modal fade" id="createVersionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">创建新版本</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="versionForm">
                        <div class="mb-3">
                            <div class="alert alert-info d-flex align-items-center" role="alert">
                                <i class="bx bx-info-circle me-2"></i>
                                <div>当前版本: <strong id="modalCurrentVersion">加载中...</strong></div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">版本号</label>
                            <input type="text" class="form-control" id="versionNumber" required 
                                   placeholder="例如: 1.0.0" 
                                   onkeyup="validateVersion(this.value)">
                            <div id="versionFeedback" class="invalid-feedback">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">下载链接</label>
                            <input type="url" class="form-control" id="downloadUrl" required 
                                   placeholder="请输入有效的下载链接"
                                   onkeyup="validateDownloadUrl(this.value)">
                            <div id="downloadUrlFeedback" class="invalid-feedback">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="createVersion()">创建</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加版本说明模态框 -->
    <div class="modal fade" id="addDescModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加版本说明</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="descForm">
                        <input type="hidden" id="descVersionId">
                        <div class="mb-3">
                            <label class="form-label">更新类型</label>
                            <select class="form-select" id="updateType" required>
                                <option value="0">新增</option>
                                <option value="1">优化</option>
                                <option value="2">修复</option>
                                <option value="3">删除</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">更新内容</label>
                            <textarea class="form-control" id="updateContent" rows="3" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addVersionDesc()">添加</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let createVersionModal;
let addDescModal;
let versionDetailModal;
let currentVersion = '';

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    createVersionModal = new bootstrap.Modal(document.getElementById('createVersionModal'));
    addDescModal = new bootstrap.Modal(document.getElementById('addDescModal'));
    versionDetailModal = new bootstrap.Modal(document.getElementById('versionDetailModal'));
    getCurrentVersion();
    loadVersions();
});

// 获取当前版本
async function getCurrentVersion() {
    try {
        const response = await fetch('/api/system/version/current/');
        const data = await response.json();
        
        if (data.code === 200) {
            currentVersion = data.data.version;
            document.getElementById('currentVersion').innerHTML = `
                <i class="bx bx-code-alt me-1"></i>
                当前版本: ${currentVersion}
            `;
            document.getElementById('modalCurrentVersion').textContent = currentVersion;
        }
    } catch (error) {
        console.error('获取当前版本失败:', error);
        showToast('获取当前版本失败', 'error');
    }
}

// 比较版本号
function compareVersions(v1, v2) {
    const parts1 = v1.split('.').map(Number);
    const parts2 = v2.split('.').map(Number);
    
    for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
        const num1 = parts1[i] || 0;
        const num2 = parts2[i] || 0;
        
        if (num1 > num2) return 1;
        if (num1 < num2) return -1;
    }
    return 0;
}

// 加载版本列表
async function loadVersions() {
    try {
        const response = await fetch('/api/system/version/');
        const data = await response.json();
        
        if (data.code === 200) {
            renderVersions(data.data);
        }
    } catch (error) {
        console.error('加载版本列表失败:', error);
        showToast('加载版本列表失败', 'error');
    }
}

// 渲染版本列表
function renderVersions(versions) {
    const container = document.getElementById('versionList');
    if (!versions || !Array.isArray(versions) || versions.length === 0) {
        container.innerHTML = `
            <div class="col-12">
                <div class="card">
                    <div class="card-body text-center py-5">
                        <i class="bx bx-info-circle fs-1 text-muted mb-3"></i>
                        <p class="mb-0">暂无版本记录</p>
                    </div>
                </div>
            </div>
        `;
        return;
    }

    container.innerHTML = versions.map(version => `
        <div class="col-md-6 col-lg-4">
            <div class="card version-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">版本 ${version.version}</h5>
                    <div>
                        <button class="btn btn-info btn-sm me-2" 
                                onclick="showVersionDetail('${version.version}', '${version.create_time}', '${version.download_url}')">
                            <i class="bx bx-info-circle me-1"></i> 详情
                        </button>
                        <button class="btn btn-primary btn-sm" 
                                onclick="openAddDescModal('${version.version}')">
                            添加说明
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <small class="text-muted">
                            发布时间: ${new Date(version.create_time).toLocaleString()}
                        </small>
                        <br>
                        <small class="text-muted">
                            下载链接: <a href="${version.download_url}" target="_blank">点击下载</a>
                        </small>
                    </div>
                    <div class="version-desc-list desc-collapse ${version.descriptions?.length > 3 ? 'collapsed' : ''}">
                        ${(version.descriptions || []).map(desc => `
                            <div class="mb-2">
                                <span class="badge type-badge-${getDescTypeClass(desc.type)} me-2">
                                    ${desc.type}
                                </span>
                                ${desc.text}
                            </div>
                        `).join('')}
                    </div>
                    ${version.descriptions?.length > 3 ? `
                        <div class="show-more-btn" onclick="toggleDescCollapse(this)">
                            <i class="bx bx-chevron-down"></i> 显示更多
                        </div>
                    ` : ''}
                </div>
            </div>
        </div>
    `).join('');
}

// 打开创建版本模态框
function openCreateVersionModal() {
    document.getElementById('versionForm').reset();
    document.getElementById('versionNumber').classList.remove('is-invalid');
    document.getElementById('downloadUrl').classList.remove('is-invalid', 'is-valid');
    createVersionModal.show();
}

// 打开添加说明模态框
function openAddDescModal(version) {
    document.getElementById('descForm').reset();
    document.getElementById('descVersionId').value = version;
    addDescModal.show();
}

// 创建新版本
async function createVersion() {
    try {
        const newVersion = document.getElementById('versionNumber').value;
        const downloadUrl = document.getElementById('downloadUrl').value;
        
        // 验证必填字段
        if (!newVersion || !downloadUrl) {
            showToast('版本号和下载链接都是必填项', 'error');
            
            // 显示具体哪个字段未填写
            const versionInput = document.getElementById('versionNumber');
            const downloadInput = document.getElementById('downloadUrl');
            
            if (!newVersion) {
                versionInput.classList.add('is-invalid');
                document.getElementById('versionFeedback').textContent = '请填写版本号';
            }
            
            if (!downloadUrl) {
                downloadInput.classList.add('is-invalid');
                document.getElementById('downloadUrlFeedback').textContent = '请填写下载链接';
            }
            return;
        }
        
        // 验证版本号格式
        if (!/^\d+\.\d+\.\d+$/.test(newVersion)) {
            showToast('版本号格式错误，请使用 x.y.z 格式（如 1.0.0）', 'error');
            return;
        }
        
        // 验证新版本是否大于当前版本
        const compareResult = compareVersions(newVersion, currentVersion);
        if (compareResult < 0) {
            showToast('新版本号不能小于当前版本', 'error');
            return;
        }
        if (compareResult === 0) {
            showToast('新版本号不能等于当前版本', 'error');
            return;
        }

        // 验证下载链接格式
        try {
            new URL(downloadUrl);
        } catch (e) {
            showToast('请输入有效的下载链接', 'error');
            downloadInput.classList.add('is-invalid');
            document.getElementById('downloadUrlFeedback').textContent = '请输入有效的下载链接';
            return;
        }

        const formData = new FormData();
        formData.append('version', newVersion);
        formData.append('download_url', downloadUrl);

        const response = await fetch('/api/system/version/create/', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        if (data.code === 200) {
            showToast('创建版本成功', 'success');
            createVersionModal.hide();
            loadVersions();
        } else {
            showToast(data.message, 'error');
        }
    } catch (error) {
        console.error('创建版本失败:', error);
        showToast('创建版本失败', 'error');
    }
}

// 添加版本说明
async function addVersionDesc() {
    try {
        const formData = new FormData();
        formData.append('version', document.getElementById('descVersionId').value);
        formData.append('type', document.getElementById('updateType').value);
        formData.append('text', document.getElementById('updateContent').value);

        const response = await fetch('/api/system/version/desc/', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        if (data.code === 200) {
            showToast('添加说明成功', 'success');
            addDescModal.hide();
            loadVersions();
        } else {
            showToast(data.message, 'error');
        }
    } catch (error) {
        console.error('添加说明失败:', error);
        showToast('添加说明失败', 'error');
    }
}

// 获取更新类型文本
function getTypeText(type) {
    return type || '未知';
}

// 显示通知
function showToast(message, type = 'success') {
    const container = document.querySelector('.toast-container') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast-notification toast-${type}`;
    
    const closeBtn = document.createElement('button');
    closeBtn.className = 'btn-close';
    closeBtn.onclick = () => toast.remove();
    
    let icon;
    switch (type) {
        case 'success':
            icon = '<i class="bx bx-check-circle me-2"></i>';
            break;
        case 'error':
            icon = '<i class="bx bx-x-circle me-2"></i>';
            break;
        case 'warning':
            icon = '<i class="bx bx-error-circle me-2"></i>';
            break;
    }
    
    toast.innerHTML = `
        <div class="d-flex align-items-center">
            ${icon}
            <span>${message}</span>
        </div>
    `;
    toast.appendChild(closeBtn);
    
    container.appendChild(toast);
    
    setTimeout(() => {
        if (toast && toast.parentElement) {
            toast.style.animation = 'fadeOut 0.3s ease forwards';
            setTimeout(() => toast.remove(), 300);
        }
    }, 3000);
}

// 创建通知容器
function createToastContainer() {
    const container = document.createElement('div');
    container.className = 'toast-container';
    document.body.appendChild(container);
    return container;
}

// 验证版本号
function validateVersion(value) {
    const input = document.getElementById('versionNumber');
    const feedback = document.getElementById('versionFeedback');
    
    // 清除之前的状态
    input.classList.remove('is-invalid', 'is-valid');
    
    // 如果输入为空，不显示任何提示
    if (!value) return;
    
    // 验证格式
    if (!/^\d+\.\d+\.\d+$/.test(value)) {
        input.classList.add('is-invalid');
        feedback.textContent = '版本号格式错误，请使用 x.y.z 格式（如 1.0.0）';
        return;
    }
    
    // 验证版本号大小
    const compareResult = compareVersions(value, currentVersion);
    if (compareResult < 0) {
        input.classList.add('is-invalid');
        feedback.textContent = '新版本号不能小于当前版本';
        return;
    }
    if (compareResult === 0) {
        input.classList.add('is-invalid');
        feedback.textContent = '新版本号不能等于当前版本';
        return;
    }
    
    // 验证通过
    input.classList.add('is-valid');
}

// 验证下载链接
function validateDownloadUrl(value) {
    const input = document.getElementById('downloadUrl');
    const feedback = document.getElementById('downloadUrlFeedback');
    
    // 清除之前的状态
    input.classList.remove('is-invalid', 'is-valid');
    
    // 如果输入为空，不显示任何提示
    if (!value) return;
    
    // 验证URL格式
    try {
        new URL(value);
        input.classList.add('is-valid');
    } catch (e) {
        input.classList.add('is-invalid');
        feedback.textContent = '请输入有效的下载链接';
    }
}

// 显示版本详情
async function showVersionDetail(version, createTime, downloadUrl) {
    try {
        // 设置基本信息
        document.getElementById('detailVersionNumber').textContent = `版本 ${version}`;
        document.getElementById('detailCreateTime').textContent = `发布时间: ${new Date(createTime).toLocaleString()}`;
        document.getElementById('detailDownloadUrl').href = downloadUrl;
        
        // 获取并显示版本说明
        const response = await fetch(`/api/system/version/desc/?version=${version}`);
        const data = await response.json();
        
        if (data.code === 200) {
            const descList = document.getElementById('detailDescList');
            if (data.data && data.data.length > 0) {
                descList.innerHTML = data.data.map(desc => `
                    <div class="alert alert-${getDescTypeClass(desc.type)} mb-3">
                        <div class="d-flex align-items-center">
                            <span class="badge type-badge-${getDescTypeClass(desc.type)} me-2">
                                ${desc.type}
                            </span>
                            <div>${desc.text}</div>
                        </div>
                    </div>
                `).join('');
            } else {
                descList.innerHTML = '<div class="text-center text-muted">暂无更新说明</div>';
            }
        }
        
        versionDetailModal.show();
    } catch (error) {
        console.error('获取版本详情失败:', error);
        showToast('获取版本详情失败', 'error');
    }
}

// 获取说明类型对应的样式类
function getDescTypeClass(type) {
    const typeMap = {
        '新增': 'primary',
        '优化': 'info',
        '修复': 'danger',
        '删除': 'secondary'
    };
    return typeMap[type] || 'primary';
}

// 切换版本说明折叠状态
function toggleDescCollapse(btn) {
    const descList = btn.previousElementSibling;
    const isCollapsed = descList.classList.contains('collapsed');
    
    if (isCollapsed) {
        descList.classList.remove('collapsed');
        btn.innerHTML = '<i class="bx bx-chevron-up"></i> 收起';
    } else {
        descList.classList.add('collapsed');
        btn.innerHTML = '<i class="bx bx-chevron-down"></i> 显示更多';
    }
}
</script>
{% endblock %}

{% block nav_left %}
{% include "后台管理/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}{% endblock %}

{% block footer %}{% include '后台管理/components/Footer.html' %}{% endblock %}


